package com.iyao_app.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.iyao_app.R;


import java.lang.reflect.Field;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/14.
 */

public abstract class BaseFragment extends Fragment  {
    /**
     * 根元素
     */
    protected View rootView;
    /**
     * 布局渲染工具
     */
    protected LayoutInflater mInflater;
    protected Context mContext;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mInflater = inflater;
        mContext = inflater.getContext();
        rootView = initRootView(inflater);
        return rootView;
    }

    public void setTitleTV(String str) {
        TextView tv_title = rootView.findViewById(R.id.tv_title);
        tv_title.setText(str);
    }

    public void back(View view) {
        finish();
    }

    public void setNextImage(int resId) {
        ImageView iv_next = rootView.findViewById(R.id.iv_next);
        iv_next.setImageResource(resId);
    }

    public void onNextClick(View.OnClickListener onClickListener) {
        ImageView iv_next = rootView.findViewById(R.id.iv_next);
        iv_next.setOnClickListener(onClickListener);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setViews();
        initData();
    }

    /**
     * 初始化View,加载布局
     *
     * @return 布局
     */
    public abstract View initRootView(LayoutInflater inflater);


    /**
     * 解决fragment嵌套问题:No activity
     */
    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class
                    .getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {


    }

    public void finish() {
        getActivity().finish();
    }

    /**
     * 初始化数据
     */
    public abstract void setViews();

    /**
     * 加载网络数据
     */
    public abstract void initData();


}
